<template>
  <div class="author-container">
    <!-- 头部信息 -->
    <div class="author-header">
      <div class="header-main">
        <div class="avatar-section">
          <el-tooltip :content="authorInfo.avatar" placement="top">
            <author-avatar :size="100" :avatar="authorInfo.avatar" :show-hover-info="false" />
          </el-tooltip>
          <div class="name-section">
            <h1>{{ authorInfo.nickname }}</h1>
            <template v-if="!isAuthorSelf">
              <el-button
                v-if="!isAttention"
                type="primary"
                round
                class="follow-button"
                @click="attentionAuthor"
              >
                关注
              </el-button>
              <el-button v-else type="info" round class="follow-button" @click="unAttentionAuthor">
                取消关注
              </el-button>
            </template>
          </div>
        </div>
        <!-- 统计面板 -->
        <div class="stats-section">
          <div class="stat-item">
            <el-icon class="stat-icon">
              <user />
            </el-icon>
            <span class="stat-number">{{ authorInfo.follower }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item">
            <el-icon class="stat-icon">
              <star />
            </el-icon>
            <span class="stat-number">{{ authorInfo.attention }}</span>
            <span class="stat-label">关注</span>
          </div>
          <div class="stat-item">
            <el-icon class="stat-icon">
              <document />
            </el-icon>
            <span class="stat-number">{{ authorInfo.articleNum }}</span>
            <span class="stat-label">文章</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="author-content">
      <!-- 左侧文章列表 -->
      <div v-loading="loading" class="main-content">
        <div class="list-header">
          <el-tabs v-model="activeTab" class="custom-tabs">
            <el-tab-pane label="已发布" name="published" />
            <el-tab-pane v-if="isAuthorSelf" label="草稿" name="draft" />
          </el-tabs>
          <div class="header-right">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索文章标题或内容"
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search-icon /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="sortBy"
              placeholder="排序方式"
              size="default"
              class="sort-method"
              @change="handleSort"
            >
              <el-option label="最新发布" value="publishTime">
                <el-icon><timer /></el-icon>
                <span style="margin-left: 8px">最新发布</span>
              </el-option>
              <el-option label="最多访问" value="blogViews">
                <el-icon><view-icon /></el-icon>
                <span style="margin-left: 8px">最多访问</span>
              </el-option>
              <el-option label="最多点赞" value="likes">
                <svg-icon icon-class="like" />
                <span style="margin-left: 8px">最多点赞</span>
              </el-option>
            </el-select>
            <el-radio-group
              v-model="sortOrder"
              size="small"
              style="flex-wrap: nowrap"
              @change="handleSort"
            >
              <el-radio-button label="desc">降序</el-radio-button>
              <el-radio-button label="asc">升序</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 文章列表内容 -->
        <div v-show="activeTab === 'published'" class="tab-content">
          <template v-if="publishedArticles.length > 0">
            <div v-for="article in publishedArticles" :key="article.blogId" class="article-item">
              <h3 class="article-title">
                <!-- 标题部分 -->
                <router-link
                  :to="{
                    name: 'blogViewShow',
                    params: { blogId: article.blogId }
                  }"
                  class="blog-title"
                >
                  <el-text>{{ article.blogTitle }}</el-text>
                </router-link>
              </h3>
              <el-text line-clamp="3" style="flex-grow: 1; margin-right: 10px">
                {{ cleanTextContent(article.blogContent) }}
              </el-text>
              <div class="article-meta">
                <span class="publish-time">
                  <el-icon><timer /></el-icon>
                  {{ article.publishTime }}
                </span>
                <div class="meta-right">
                  <span class="read-count">
                    <el-icon><view-icon /></el-icon>
                    {{ article.blogViews }}
                  </span>
                  <span class="like-count">
                    <svg-icon icon-class="like" />
                    {{ article.likes }}
                  </span>
                </div>
              </div>
            </div>
            <el-pagination
              v-model:current-page="publishedPagination.pageNum"
              :page-size="publishedPagination.pageSize"
              :total="publishedPagination.total"
              background
              layout="prev, pager, next"
              class="pagination"
              @current-change="handlePageChange"
            />
          </template>
          <el-empty v-else description="无数据" />
        </div>

        <div v-show="activeTab === 'draft'" class="tab-content">
          <template v-if="draftArticles.length > 0">
            <div
              v-for="article in draftArticles"
              :key="article.blogId"
              class="article-item draft-item"
            >
              <h3 class="article-title">
                <!-- 标题部分 -->
                <router-link
                  :to="{
                    name: 'blogViewShow',
                    params: { blogId: article.blogId }
                  }"
                  class="blog-title"
                >
                  <el-text>{{ article.blogTitle }}</el-text>
                </router-link>
              </h3>
              <el-text line-clamp="3" style="flex-grow: 1; margin-right: 10px">
                {{ cleanTextContent(article.blogContent) }}
              </el-text>
              <div class="article-meta">
                <span class="publish-time">
                  <el-icon><timer /></el-icon>
                  {{ article.publishTime }}
                </span>
                <span class="update-time">
                  <el-icon><edit /></el-icon>
                  {{ article.updateTime }}
                </span>
              </div>
            </div>
            <el-pagination
              v-model:current-page="draftPagination.pageNum"
              :page-size="draftPagination.pageSize"
              :total="draftPagination.total"
              background
              layout="prev, pager, next"
              class="pagination"
              @current-change="handleDraftPageChange"
            />
          </template>
          <el-empty v-else description="无数据" />
        </div>
      </div>

      <!-- 右侧侧边栏 -->
      <div class="sidebar">
        <!-- 作者简介 -->
        <el-card class="info-card">
          <h3>作者简介</h3>
          <div v-if="isAuthorSelf">
            <el-input v-if="isEditingBio" v-model="editedBio" type="textarea" :rows="3" />
            <p v-else>
              {{ authorInfo.description }}
            </p>
            <div class="bio-actions">
              <template v-if="isEditingBio">
                <el-button type="primary" @click="saveBio">保存</el-button>
                <el-button type="info" @click="isEditingBio = false">取消</el-button>
              </template>
              <el-button v-else type="text" @click="startEditBio">编辑</el-button>
            </div>
          </div>
          <p v-else>
            {{ authorInfo.description }}
          </p>
        </el-card>

        <!-- 成就徽章 -->
        <el-card class="achievement-card">
          <h3>成就勋章</h3>
          <div class="badges">
            <el-tag v-for="badge in badges" :key="badge" type="info" class="badge-item">
              {{ badge.name }}
            </el-tag>
          </div>
        </el-card>

        <!-- 分类统计 -->
        <el-card class="category-card">
          <h3>分类专栏</h3>
          <div
            v-for="c in statistics.categories"
            :key="c.categoryName"
            class="category-item"
            @click="goToCategory(c.categoryId)"
          >
            <span class="category-name">{{ c.categoryName }}</span>
            <span class="category-count">{{ c.count }}篇</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getAuthorDetailById } from '@/api/author';
import { AuthorDetailVO, UserGrowthVO } from '@/api/author/types';
import { pageBlogCards } from '@/api/blog';
import { BlogInfo } from '@/api/blog/types';
import { BlogCategoryVO } from '@/api/category/types';
import AuthorAvatar from '@/components/AuthorAvatar/index.vue';
import { AUDIT_STATUS } from '@/constants/common/audit-status';
import { BLOG_STATUS } from '@/constants/common/blog-status';
import { useUserStore } from '@/store/modules/user';
import { cleanTextContent } from '@/utils';
import {
  Document,
  Edit,
  Search as SearchIcon,
  Star,
  Timer,
  User,
  View as ViewIcon
} from '@element-plus/icons-vue';
import { snakeCase } from 'change-case';
import {
  ElButton,
  ElCard,
  ElIcon,
  ElInput,
  ElPagination,
  ElRadioButton,
  ElRadioGroup,
  ElSelect,
  ElTabPane,
  ElTabs,
  ElTag,
  ElTooltip
} from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const UserStore = useUserStore();
const authorId = ref(route.params.authorId as string);

// 作者数据
const authorInfo = ref<AuthorDetailVO>({});

const badges = ref<UserGrowthVO[]>([]);

// 文章数据
const publishedArticles = ref([] as BlogInfo[]);

const draftArticles = ref([] as BlogInfo[]);

// 统计信息
const statistics = ref({ categories: [] as BlogCategoryVO[] });

// 分页
const publishedPagination = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0
});
const draftPagination = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0
});

// 编辑简介
const isAuthorSelf = ref(true);
const isEditingBio = ref(false);
const editedBio = ref('');
const activeTab = ref('published');

const startEditBio = () => {
  editedBio.value = authorInfo.value.description;
  isEditingBio.value = true;
};

const saveBio = () => {
  authorInfo.value.description = editedBio.value;
  isEditingBio.value = false;
  // 这里可以添加保存到后端的逻辑
};

// 分类跳转
const router = useRouter();
const goToCategory = (categoryId: number) => {
  router.push(`/blogList/${categoryId}`);
};

// 分页切换
const handlePageChange = async (page: number) => {
  // 根据页码加载数据
  try {
    loading.value = true;
    await pagepageBlogCards(page, 'published');
  } finally {
    loading.value = false;
  }
};
const handleDraftPageChange = async (page: number) => {
  // 根据页码加载数据
  try {
    loading.value = true;
    await pagepageBlogCards(page, 'draft');
  } finally {
    loading.value = false;
  }
};

const loading = ref(false);
const searchKeyword = ref('');
const sortBy = ref('publishTime');
const sortOrder = ref('desc');

// 搜索处理
const handleSearch = () => {
  if (activeTab.value === 'published') {
    search('published');
  } else {
    search('draft');
  }
};

// 排序处理
const handleSort = () => {
  if (activeTab.value === 'published') {
    search('published');
  } else {
    search('draft');
  }
};

const search = async (type: string) => {
  try {
    loading.value = true;
    const searchParams = {
      keyword: searchKeyword.value,
      sortField: snakeCase(sortBy.value),
      asc: sortOrder.value === 'asc'
    };
    if (type === 'published') {
      await pagepageBlogCards(publishedPagination.pageNum, 'published', searchParams);
    } else {
      await pagepageBlogCards(draftPagination.pageNum, 'draft', searchParams);
    }
  } finally {
    loading.value = false;
  }
};

const pagepageBlogCards = (page: number, type: string, searchParams?: any) => {
  if (type === 'published') {
    pageBlogCards({
      ...publishedPagination,
      pageNum: page,
      blogStatus: BLOG_STATUS.PUBLISHED,
      reviewStatus: AUDIT_STATUS.APPROVED,
      userId: authorId.value,
      ...searchParams
    }).then(response => {
      publishedArticles.value = response.data.list;
      publishedPagination.total = response.data.total;
    });
  } else {
    pageBlogCards({
      ...publishedPagination,
      pageNum: page,
      blogStatus: BLOG_STATUS.DRAFT,
      reviewStatus: AUDIT_STATUS.PENDING,
      userId: authorId.value,
      ...searchParams
    }).then(response => {
      draftArticles.value = response.data.list;
      draftPagination.total = response.data.total;
    });
  }
};

// 关注状态
const isAttention = ref(false);
// 关注
const attentionAuthor = () => {
  try {
  } finally {
    isAttention.value = true;
  }
};
// 取消关注
const unAttentionAuthor = () => {
  try {
  } finally {
    isAttention.value = false;
  }
};

onMounted(async () => {
  // 判断是否是作者本人
  isAuthorSelf.value = Number(authorId.value) === UserStore.userInfo.id;

  // 获取作者详细信息
  try {
    const res = await getAuthorDetailById(authorId.value);
    authorInfo.value = res.data.authorDetail;
    badges.value = res.data.growthList;
    isAttention.value = res.data.isAttention || res.data.isFollower;
    statistics.value.categories = res.data.blogCategoryList;
  } finally {
    console.log(authorInfo.value);
  }

  // 检索文章列表
  search('published');
  search('draft');
});
</script>

<style scoped>
.author-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.author-header {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.name-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stats-section {
  display: flex;
  gap: 20px;
  height: 80px;
  align-items: center;
  background: #f5f7fa;
  padding: 0 20px;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0px 20px;
}

.stat-icon {
  font-size: 24px;
  color: #409eff;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.author-content {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.main-content {
  flex: 3;
}

.sidebar {
  flex: 1;
}

.article-item {
  background: #fff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
.article-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.article-item.draft-item {
  border: 1px dashed #dcdfe6;
  background: #fafafa;
}

.article-title {
  margin-bottom: 8px;
}

.blog-title {
  display: inline-block;
  font-size: 1.25rem;
  text-decoration: none;
  transition:
    color 0.2s,
    box-shadow 0.2s;
  border-radius: 4px;

  .el-text {
    font-size: 1.25rem;
    text-decoration: none;
  }
}
.blog-title:hover {
  color: #409eff;
  background: #f0f7ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
  text-decoration: underline;
  cursor: pointer;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  margin-top: 10px;
}

.meta-right {
  display: flex;
  gap: 15px;
}

.info-card {
  margin-bottom: 20px;
}

.achievement-card {
  margin-bottom: 20px;
}

.badges {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.badge-item {
  background-color: #409eff;
  color: #fff;
  padding: 5px 10px;
  border-radius: 10px;
  transition: transform 0.3s ease;
}
.badge-item:hover {
  transform: scale(1.1);
}

.category-card {
  margin-bottom: 20px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.category-item:hover {
  background-color: #f5f7fa;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.follow-button:hover {
  background-color: #409eff;
  transform: scale(1.05);
  transition: all 0.3s ease;
}

.bio-actions {
  margin-top: 10px;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  background: #fff;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 56px;
}

.custom-tabs {
  flex-shrink: 0;
  margin-right: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
  height: 100%;
}

.search-input {
  min-width: 300px;
}

.sort-method {
  min-width: 100px;
}

.tab-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
